package com.lykj.modules.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lykj.core.secure.utils.AuthUtil;
import com.lykj.modules.system.entity.UserAddress;
import com.lykj.modules.system.mapper.UserAddressMapper;
import com.lykj.modules.system.service.UserAddressService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 服务实现类
 *
 * @author cxl
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements UserAddressService {


    /**
     * 删除收货地址
     *
     * @param addressId
     * @return
     */
    @Override
    public Boolean shippingAddressDelete(String addressId) {
        Long userId = AuthUtil.getUserId();
        if(userId < 1) throw new RuntimeException("登录失效,请重新登录!");
        UserAddress userAddress = baseMapper.selectById(addressId);
        if(null == userAddress) return false;
        if(userAddress.getDeleted())return true;
        if(userAddress.getUid().equals(userId)){
            userAddress.setDeleted(true);
            baseMapper.updateById(userAddress);
            return true;
        }
        return false;
    }

    /**
     * 查询收货地址列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<UserAddress> addressList(Long userId) {
        if(userId < 1) throw new RuntimeException("登录失效,请重新登录!");
        return baseMapper.selectList(
                Wrappers
                        .<UserAddress>query()
                        .lambda()
                        .eq(UserAddress::getUid, userId)
                        .eq(UserAddress::getDeleted,false)
                        .orderByDesc(UserAddress::getAddressId)
        );
    }

    /**
     * 添加收货地址
     *
     * @param userAddress
     * @return
     */
    @Override
    public UserAddress shippingAddressAdd(UserAddress userAddress) {
        Long userId = AuthUtil.getUserId();
        if(userId < 1) throw new RuntimeException("登录失效,请重新登录!");
        userAddress.setUid(AuthUtil.getUserId());
        userAddress.setDeleted(false);
        userAddress.setAddressId(null);
        if(userAddress.getIsDefault()){
            baseMapper.updateIsDefaultFalse(userAddress.getUid());
        }
        baseMapper.insert(userAddress);
        return userAddress;
    }

    /**
     * 设为默认收货地址
     *
     * @param addressId
     * @return
     */
    @Override
    public Boolean shippingAddressAsDefault(String addressId) {
        Long userId = AuthUtil.getUserId();
        if(userId < 1) throw new RuntimeException("登录失效,请重新登录!");
        baseMapper.shippingAddressAsDefault(userId,addressId);
        return true;
    }
}
